using System;
using System.Collections;
using UnityEngine;
using System.IO;
using System.Threading;
public class InputStream : myReader
{
    const int INTERVAL = 5;
    const int MAXTIME = 100;
    MemoryStream ms;
    public static InputStream istemp;
    static int status;
    static string filenametemp;
    //0: free
    //1: working
    //2: waiting
    public static void update()
    {
        if (status == 2)
        {
            status = 1;
            istemp = __loadResourceAsStream(filenametemp);
            status = 0;
        }
    }
    public static InputStream loadResourceAsStream(string filename)
    {
        if (Thread.CurrentThread.Name == Main.mainThreadName)
        {
            Debug.Log("zzzzzzzzzzzzzzzzzzzzzzzzz");
            return __loadResourceAsStream(filename);
        }
        else
            return _loadResourceAsStream(filename);
    }

    private static InputStream _loadResourceAsStream(string filename)
    {
        if (status != 0)
        {
         
            Debug.LogError("CANNOT GET INPUTSTREAM " + filename + " WHEN GETTING " + filenametemp);
            return null;
        }
        istemp = null;
        filenametemp = filename;
        status = 2;
        int i = 0;
        while (i < MAXTIME)
        {
            Thread.Sleep(INTERVAL);
            if (status == 0) break; // create done
            i++;
        }
        if (i == MAXTIME) Debug.LogError("TOO LONG FOR CREATE INPUTSTREAM " + filename);
        else Debug.Log("Create Inputstream " + filename + " done in " + (i * INTERVAL) + "ms");
        return istemp;

    }
    private static InputStream __loadResourceAsStream(string filename)
    {
        Debug.Log("yyyyyyyyyyyyyyyyyyy");
        return new InputStream(filename);
    }
    protected InputStream(string filename)
    {
        TextAsset ta = (TextAsset)Resources.Load(filename, typeof(TextAsset));
        Debug.Log("TA --> "+ta);
        ms = new MemoryStream(ta.bytes);
        Debug.Log("MS --> "+ms);
    }
    public int readByte()
    {
        return ms.ReadByte();
    }
}


